package com.zcsy.manage.web.base;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.ShopCategory;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.base.ShopInfoView;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.base.ShopInfoDao;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.IShopCategoryService;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Title: ShopInfoController.java @Package： com.zcsy.manage.web.base
 * @Description: 商铺信息控制器
 * @author zhangsh zsh3384027@gmail.com
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 * @date 2016年4月15日
 * @version 1.0
 * @see JDK1.8.0_45
 * @since
 */

@Controller
@RequestMapping(value = "/shopInfo")
public class ShopInfoController {
    /** 新入驻 */
    private static final int STATE_NEW = 1;
    /** 正常 */
    private static final int STATE_SUCCESS = 2;
    /** 禁用 */
    private static final int STAET_FORBIDEN = 3;
    /** 审核未通过 */
    private static final int STAET_NOTAPPROVE = 5;

    @Autowired
    private IShopInfoService shopInfoService;

    @Autowired
    private ICellInfoService cellInfoService;

    @Autowired
    private IShopCategoryService shopCategoryService;

    @Autowired
    private ShopInfoDao shopInfoDao;

    @Autowired
    private IDictService dictService;

    /**
     * @Description 店铺已申请信息列表
     * @author zhangsh zsh3384027@gmail.com
     * @date 2016年4月18日
     * @see
     */
    @RequestMapping(value = "/shopInfoList", method = RequestMethod.GET)
    public String shopInfoList(Model model, Integer approveState, Integer pNo, Integer pSize, String name,
            HttpServletRequest req) {
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

        Integer pageSize;
        if (pSize == null) {
            pageSize = Constants.PAGE_SIZE;
        } else {
            switch (pSize) {
            case 0:
                pageSize = Constants.PAGE_SIZE;
                break;
            case 1:
                pageSize = Constants.PAGE_SIZE_TWENTY;
                break;
            case 2:
                pageSize = Constants.PAGE_SIZE_FIFTY;
                break;
            default:
                pageSize = Constants.PAGE_SIZE;
                break;
            }
        }

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        ShopInfo shopInfo = new ShopInfo();

        // 获取当前小区id
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();

        if (StringUtils.isNotEmpty(name)) {
            shopInfo.setName(name);
        }
        if (null != approveState) {
            shopInfo.setState(approveState);
        }
        shopInfo.setCellId(cellId);

        List<ShopInfoView> list = shopInfoService.selectByKeyword(shopInfo);
        PageInfo<ShopInfoView> shopinfoList = new PageInfo<ShopInfoView>(list);

        model.addAttribute("shopinfoList", shopinfoList);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("pSize", pSize);
        model.addAttribute("name", name);
        model.addAttribute("belong", 1);

        List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
        model.addAttribute("pageSizes", pageSizes);

        return "base/shopinfo/shopInfoList";
    }

    /**
     * @Description 店铺新申请信息列表
     * @author zhangsh zsh3384027@gmail.com
     * @date 2016年4月18日
     * @see
     */
    @RequestMapping(value = "/newShopInfoList", method = RequestMethod.GET)
    public String newshopInfoList(Model model, Integer pNo, Integer pSize, String name, HttpServletRequest req) {
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

        Integer pageSize;
        if (pSize == null) {
            pageSize = Constants.PAGE_SIZE;
        } else {
            switch (pSize) {
            case 0:
                pageSize = Constants.PAGE_SIZE;
                break;
            case 1:
                pageSize = Constants.PAGE_SIZE_TWENTY;
                break;
            case 2:
                pageSize = Constants.PAGE_SIZE_FIFTY;
                break;
            default:
                pageSize = Constants.PAGE_SIZE;
                break;
            }
        }

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        ShopInfo shopInfo = new ShopInfo();
        if (StringUtils.isNotEmpty(name)) {
            shopInfo.setName(name);
        }
        shopInfo.setState(0);
        List<ShopInfoView> list = shopInfoService.selectByKeyword(shopInfo);
        PageInfo<ShopInfoView> shopinfoList = new PageInfo<ShopInfoView>(list);

        model.addAttribute("shopinfoList", shopinfoList);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("pSize", pSize);
        model.addAttribute("name", name);
        model.addAttribute("belong", 2);

        List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
        model.addAttribute("pageSizes", pageSizes);

        return "base/shopinfo/shopInfoList";
    }

    /**
     * @Description 商户信息详情
     * @author zhangsh zsh3384027@gmail.com
     * @date 2016年4月18日
     * @see
     */
    @RequestMapping(value = "/shopInfoDetail", method = RequestMethod.GET)
    public String detailInfo(Model model, String id, HttpServletRequest req) {
        ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(id);
        CellInfo cellInfo = new CellInfo();
        ShopCategory shopCategory = new ShopCategory();
        /*
         * DistrictInfo licenseProvinceid = new DistrictInfo(); DistrictInfo
         * licenseCityid = new DistrictInfo(); DistrictInfo licenseAreaid = new
         * DistrictInfo(); DistrictInfo companyProvinceid = new DistrictInfo();
         * DistrictInfo companyCityid = new DistrictInfo(); DistrictInfo
         * companyAreaid= new DistrictInfo();
         */
        if (shopInfo != null) {
            cellInfo = cellInfoService.selectByPrimaryKey(shopInfo.getCellId());
            /*
             * licenseProvinceid =
             * districtInfoService.getDistrictInfoById(Integer.getInteger(
             * shopInfo.getBusinessLicenseProvinceid())); licenseCityid =
             * districtInfoService.getDistrictInfoById(Integer.getInteger(
             * shopInfo.getBusinessLicenseCityid())); licenseAreaid =
             * districtInfoService.getDistrictInfoById(Integer.getInteger(
             * shopInfo.getBusinessLicenseAreaid())); companyProvinceid =
             * districtInfoService.getDistrictInfoById(Integer.getInteger(
             * shopInfo.getCompanyProvinceid())); companyCityid =
             * districtInfoService.getDistrictInfoById(Integer.getInteger(
             * shopInfo.getCompanyCityid())); companyAreaid =
             * districtInfoService.getDistrictInfoById(Integer.getInteger(
             * shopInfo.getCompanyAreaid()));
             */
            shopCategory = shopCategoryService.selectByPrimaryKey(shopInfo.getShopCategoryId());
        }
        model.addAttribute("shopinfo", shopInfo);
        model.addAttribute("cellInfo", cellInfo);
        /*
         * model.addAttribute("licenseProvinceid", licenseProvinceid);
         * model.addAttribute("licenseCityid", licenseCityid);
         * model.addAttribute("licenseAreaid", licenseAreaid);
         * model.addAttribute("companyProvinceid", companyProvinceid);
         * model.addAttribute("companyCityid", companyCityid);
         * model.addAttribute("companyAreaid", companyAreaid);
         */
        model.addAttribute("shopCategory", shopCategory);
        return "base/shopinfo/shopInfoDetail";
    }

    /**
     * @Description 商户操作
     * @author zhangsh zsh3384027@gmail.com
     * @date 2016年4月18日
     * @see
     */
    @RequestMapping(value = "/shopInfoUpdate", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson shopInfoUpdate(Model model, String id, int state, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        int temp = 0;
        try {
            ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(id);
            switch (state) {
            case STATE_NEW:
                temp = STATE_SUCCESS;
                break;
            case STATE_SUCCESS:
                temp = STAET_FORBIDEN;
                break;
            case STAET_FORBIDEN:
                temp = STATE_SUCCESS;
                break;
            default:
                temp = STAET_NOTAPPROVE;
                break;
            }
            shopInfo.setState(temp);
            shopInfoService.update(shopInfo);
            LogUtils.insertLog("用户更新店铺状态", user.getId(), req);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 根据排序实现置顶功能，即修改当前排序为最大排序值加1，并且更新修改时间<br>
     * @param id
     *            商品id
     * @param req
     *            用户请求
     * @author caiyinli 13277030520@163.com
     * @date 2016年6月3日
     * @see
     */
    @RequestMapping(value = "updateSort", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson updateSort(String id, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
            ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(id);
            if (shopInfo != null) {
                shopInfoDao.updateSort(shopInfo);
                LogUtils.insertLog("用户置顶店铺信息", user.getId(), req);
            }
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @description 商户申请审核列表
     * @author chenxin
     * @date 2016年8月18日下午1:22:26
     */
    @RequestMapping(value = "/shopAppliacation", method = RequestMethod.GET)
    public String shopAppliacation(Model model, Integer applyState, Integer pNo, Integer pSize, String name, HttpServletRequest req) {
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

        Integer pageSize;
        
        if (pSize == null) {
            pageSize = Constants.PAGE_SIZE;
        } else {
            switch (pSize) {
            case 0:
                pageSize = Constants.PAGE_SIZE;
                break;
            case 1:
                pageSize = Constants.PAGE_SIZE_TWENTY;
                break;
            case 2:
                pageSize = Constants.PAGE_SIZE_FIFTY;
                break;
            default:
                pageSize = Constants.PAGE_SIZE;
                break;
            }
        }

        ShopInfo shopInfo = new ShopInfo();

        if (StringUtils.isNotEmpty(name)) {
            shopInfo.setContactor(name);
        }
        
        // 获取当前小区信息
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        shopInfo.setCellId(cellId);
        
       if(null == applyState ) {
           applyState = Constants.STATE_ENABLED;
           shopInfo.setState(Constants.STATE_ENABLED);
       } else {
           shopInfo.setState(applyState);
       }
        
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        List<ShopInfoView> list = shopInfoService.selectByKeywords(shopInfo);
        PageInfo<ShopInfoView> shopinfoList = new PageInfo<ShopInfoView>(list);

        model.addAttribute("shopinfoList", shopinfoList);
        model.addAttribute("currentPage", pNo);
        model.addAttribute("pSize", pSize);
        model.addAttribute("name", name);
        model.addAttribute("belong", 1);
        model.addAttribute("approveState", applyState);

        List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
        model.addAttribute("pageSizes", pageSizes);
        
        List<Dict> applyingState = dictService.getDictFromCache("approveState");
        model.addAttribute("applyingState", applyingState);
        
        Integer numberOfApplying = shopInfoService.countApply(cellId);
        model.addAttribute("numberOfApplying", numberOfApplying);

        return "base/shopinfo/shopAppliacation";
    }

    /**
     * @description 商户申请--审核--更新商店状态
     * @author chenxin
     * @date 2016年8月18日下午4:19:28
     */
    @RequestMapping(value = "/shopInfoUpdating", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson shopInfoUpdating(Model model, String id, int state, String cellId, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        int temp = 0;
        try {
            ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(id);
            shopInfo.setId(id);
            switch (state) {
            case STATE_SUCCESS:
                temp = STATE_SUCCESS;
                break;
            case STAET_NOTAPPROVE:
                temp = STAET_NOTAPPROVE;
                break;
            default:
                temp = STAET_NOTAPPROVE;
                break;
            }
            shopInfo.setState(temp);
            shopInfoService.update(shopInfo);
            Integer numberOfApplying = shopInfoService.countApply(cellId);
            result.setObj(numberOfApplying);
            LogUtils.insertLog("用户审核店铺信息", user.getId(), req);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @description 更新是否为自营店
     * @author chenxin
     * @date 2016年8月18日下午4:19:28
     */
    @RequestMapping(value = "/selfStore", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson selfStore(Model model, String id, int selfstore, HttpServletRequest request) {
        RequestJson result = new RequestJson();
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        int temp = 0;
        try {
            ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(id);
            switch (selfstore) {
            case Constants.STATE_ENABLED:
                temp = Constants.STATE_DISABLED;
                break;
            case Constants.STATE_DISABLED:
                temp = Constants.STATE_ENABLED;
                break;
            default:
                temp = Constants.STATE_DISABLED;
                break;
            }
            shopInfo.setSelfStore(temp);
            shopInfoService.update(shopInfo);
            LogUtils.insertLog("用户设置店铺为自营店", user.getId(), request);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 根据多个id删除店铺信息
     * @param iDs
     *            多个id
     * @return 删除结果
     * @author liuying 1075817474@qq.com
     * @date 2016年9月1日
     * @see
     */
    @RequestMapping(value = "deleteShop", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteShop(String iDs, HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            String ids[] = iDs.split("\\,");
            for (int i = 0; i < ids.length; i++) {
                shopInfoService.deleteByPrimaryKey(ids[i]);
            }
            result.setSuccess(true);
            LogUtils.insertLog("用户删除店铺信息", user.getId(), req);

        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }

        return result;
    }
    
    /**
     * @description 展示商户申请详情
     * @param id 商户的id
     * @return
     * String
     * @author chenxin
     * @date 2016年9月14日上午8:55:02
     */
    @RequestMapping(value = "/showDetail", method = RequestMethod.GET)
    public String showDetail(Model model, String id) {
        try {

            ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(id);

            CellInfo cellInfo = cellInfoService.selectByPrimaryKey(shopInfo.getCellId());
            ShopCategory shopCategory = shopCategoryService.selectByPrimaryKey(shopInfo.getShopCategoryId());

            model.addAttribute("cellInfo", cellInfo);
            model.addAttribute("shopCategory", shopCategory);
            model.addAttribute("shopinfo", shopInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "base/shopinfo/shopAppliacationDetail";
    }
    
    /**
     * @description 后台填写商户申请备注（处理情况和进度）
     * @param id 商户的id
     * @return
     * String
     * @author chenxin
     * @date 2016年9月14日上午8:55:02
     */
    @RequestMapping(value = "/addMemo", method = RequestMethod.GET)
    public String addMemo(String id, Model model) {
        
        ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(id);
        model.addAttribute("shopInfo", shopInfo);
        return "base/shopinfo/addMemo";
    }
   
    /**
     * @description 保存商户申请备注信息
     * @param id 店铺id
     * @param memo 店铺备注信息
     * @author chenxin
     * @date 2016年9月22日下午2:04:41
     */
    @RequestMapping(value = "saveMemo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveMemo(Model model, String id, String memo, HttpServletRequest request) {
        RequestJson result = new RequestJson();
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            ShopInfo shopInfo = shopInfoService.selectByPrimaryKey(id);
            shopInfo.setMemo(memo);

            shopInfoService.update(shopInfo);
            result.setSuccess(true);
            LogUtils.insertLog("用户添加商户申请备注信息", user.getId(), request);
        } catch (Exception e) {
            result.setSuccess(false);
            e.printStackTrace();
        }
        return result;
    }

}
